#include <GameLogic.h>
#include <Actor.h>

BaseGame::BaseGame()
{
	m_pProcessManager = ALE_NEW ProcessManager();
	m_state = BGS_Initializing;
	m_lifeTime = 0;
}

BaseGame::~BaseGame()
{
	for (auto it = m_actors.begin(); it != m_actors.end(); ++it)
	{
		(*it).second->Destroy();
	}
	m_actors.clear();
	SAFE_DELETE(m_pProcessManager);
}

bool BaseGame::VPreload()
{
	return true;
}

bool BaseGame::VInit()
{
	return true;
}

bool BaseGame::VLoadGame(const char* levelRes)
{
	return true;
}

void BaseGame::VUpdate(double deltaSecs)
{
	m_lifeTime += deltaSecs;

	switch (m_state)
	{
	case BGS_Initializing:
		VChangeState(BGS_Running);
		break;

	case BGS_Running:
		m_pProcessManager->UpdateProcesses(deltaSecs);

		for (auto it = m_actors.begin(); it != m_actors.end(); ++it)
		{
			(*it).second->Update(deltaSecs);
		}
		for (auto it = m_views.begin(); it != m_views.end(); ++it)
		{
			(*it)->VUpdate(deltaSecs);
		}
	}
}

void BaseGame::VChangeState(BaseGameState newState)
{
	m_state = newState;
}

void BaseGame::VRenderViews()
{
	auto it = m_views.begin();

	while(it != m_views.end())
	{
		(*it)->VRender();
		++it;
	}
}

StrongActorPtr BaseGame::VGetActor(const ActorId id)
{
	auto it = m_actors.find(id);
	if( it == m_actors.end())
	{
		StrongActorPtr null;
		return null;
	}
	return (*it).second;
}

void BaseGame::VAddActor(StrongActorPtr pActor)
{
	ActorId destId = pActor->GetId();
	m_actors[destId] = pActor;
}

void BaseGame::VRemoveActor(ActorId id)
{
	if(VGetActor(id) != NULL)
	{
		m_actors.erase(id);
	}
}

void BaseGame::VAddView(GameViewPtr pView)
{
	int viewId = static_cast<int>(m_views.size());
	m_views.push_back(pView);
	pView->VAttach(viewId);
	pView->VRestore();
}

void BaseGame::VRemoveView(GameViewPtr pView)
{
	m_views.remove(pView);
}